﻿using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Microsoft.VisualStudio.DebuggerVisualizers;

namespace BrushVisualizer.Visualizer
{
    /// <summary>
    /// Custom serialization of a WPF Brush to a PNG bitmap
    /// </summary>
    public class BrushVisualizerObjectSource : VisualizerObjectSource
    {
        public override void GetData(object target, System.IO.Stream outgoingData)
        {
            Brush b = (Brush)target;
            // Default size of encoded image, used unless the brush specifies a better size
            Size size = new Size(100, 100);
            
            if (b is ImageBrush)
            {
                var ib = (ImageBrush)b;
                if (ib.ImageSource != null && ib.ImageSource.Width > 0 && ib.ImageSource.Height > 0)
                    size = new Size(ib.ImageSource.Width, ib.ImageSource.Height);
            }
            else if (b is VisualBrush)
            {
                var vb = (VisualBrush)b;
                var element = vb.Visual as UIElement;
                if (element != null && element.RenderSize != Size.Empty)
                    size = element.RenderSize;
            }
            else if (b is DrawingBrush)
            {
                var db = (DrawingBrush)b;
                if(db.Drawing != null && db.Drawing.Bounds != Rect.Empty)
                    size = db.Drawing.Bounds.Size;
            }
            else if (b is LinearGradientBrush || b is RadialGradientBrush)
            {
                size = new Size(200, 200);
            }
            // Draw a rectangle and paint it with the brush. The rectangle is then rendered and encoded as a bitmap so that 
            // it can be serialized to the debugger process.
            Rectangle rect = new Rectangle { Fill = b, Width = size.Width, Height = size.Height };
            rect.Measure(size);
            rect.Arrange(new Rect(size));            
            RenderTargetBitmap bmp = new RenderTargetBitmap((int)size.Width, (int)size.Height, 96, 96, PixelFormats.Default);
            bmp.Render(rect);
            var encoder = new PngBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(bmp));
            encoder.Save(outgoingData);
        }
    }
}
